package com.wukang.photovoltaicinspectionpictures.ui.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.wukang.photovoltaicinspectionpictures.R
import com.wukang.photovoltaicinspectionpictures.bean.TaskData
import com.wukang.photovoltaicinspectionpictures.databinding.DialogTaskBottomBinding
import com.wukang.photovoltaicinspectionpictures.ui.adapter.TaskListAdapter
import com.wukang.photovoltaicinspectionpictures.utils.buildList
import com.wukang.photovoltaicinspectionpictures.utils.onDebounceClick


/**
 * 任务底部弹窗
 * @author wukang
 */
class TaskBottomDialog(context: Context) : Dialog(context, R.style.Primary_BottomDialog) {
    private val mBinding: DialogTaskBottomBinding = DialogTaskBottomBinding.inflate(LayoutInflater.from(context))

    init {
        setContentView(mBinding.root)
        window?.apply {
            clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
            setAttributes(attributes?.apply {
                width = ViewGroup.LayoutParams.MATCH_PARENT
                height = ViewGroup.LayoutParams.WRAP_CONTENT
                gravity = Gravity.BOTTOM
                dimAmount = 0.5f
            })
        }
        setCanceledOnTouchOutside(false)
        setCancelable(false)
    }

    private var onTaskSelectListener: ((TaskData?) -> Unit)? = null
    private var taskListAdapter: TaskListAdapter? = null

    /**
     * 设置任务选择监听器
     */
    fun setTaskSelectListener(listener: (TaskData?) -> Unit) {
        onTaskSelectListener = listener
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // todo.. 替换真实数据
        val listData = 5.buildList {
            TaskData(
                "任务$it", "电站$it", "第${it}块",
                System.currentTimeMillis(), "相机$it", "注意事项：$it"
            )
        }
        taskListAdapter = TaskListAdapter(listData)
        mBinding.rvTaskList.adapter = taskListAdapter
        mBinding.rvTaskList.layoutManager = LinearLayoutManager(context)
        mBinding.btCancel.onDebounceClick { cancel() }
        mBinding.btConfirm.visibility = if (listData.isEmpty()) View.GONE else View.VISIBLE
        mBinding.btConfirm.onDebounceClick {
            cancel()
            onTaskSelectListener?.invoke(taskListAdapter?.getSelectTaskData())
        }
    }
}